package com.wolfking.config;

import com.wolfking.jeesite.sso.SsoLoginUrlHandler;
import com.wolfking.jeesite.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * sso 跳转登录的URL组装
 */
@Slf4j
@Component
public class ZdSsoLoginUrlHandler implements SsoLoginUrlHandler {

    @Override
    public String assemblySsoLoginUrl(String ssoLoginUrl, HttpServletRequest request) {
        try {
            if (StringUtils.isNoneBlank(ssoLoginUrl)) {
                String from = request.getParameter("from");
                if (request.getRequestURI().equals("/login") && StringUtils.isNoneBlank(from)) {
                    from = URLDecoder.decode(from, "utf-8");
                    if (from.contains("ticket=")) {
                        String prefix = from.substring(0, from.indexOf("ticket="));
                        String suffix = from.substring(from.indexOf("ticket="));
                        while (suffix.endsWith("&")) {
                            suffix = suffix.substring(0, suffix.length() - 1);
                        }
                        if (suffix.contains("&")) {
                            suffix = suffix.substring(suffix.indexOf("&") + 1);
                        } else {
                            suffix = "";
                        }
                        from = prefix + suffix;

                    }
                    return ssoLoginUrl + "?service=" + URLEncoder.encode(from, "utf-8");
                } else {
                    return ssoLoginUrl + "?service=" + RequestUtil.getRequestUrlEncode(request, "ticket");
                }
            } else {
                log.warn("config sso_jump_login_url is empty");
                return "";
            }
        } catch (Exception e) {
            log.error("", e);
            return "";
        }
    }
}
